package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Enumeration;

/**
 * @author ：mengchao
 * @date ：Created in 2020/2/14 13:46
 * @description：测试
 */
@Controller
public class TestController {

//    @RequestMapping({"/","index"})
//    @ResponseBody
//    public String index(){
//        return "我是提交代码自动构建的内容";
//    }

    @RequestMapping("test")
    public@ResponseBody
    String test(){
        return "TestController::test";
    }
    @RequestMapping("testHtml")
    public String testHtml(){
        return "testHtml";
    }

    @RequestMapping({"/", "index", "testjsp"})
    public String testjsp(String pageNum, Model model) {
        if (ObjectUtils.isEmpty(pageNum)) {
            pageNum = "null";
        }
        String hostname = "";
        BufferedReader fileReader = null;
        try {
            fileReader = new BufferedReader(new FileReader("/etc/hostname"));
            hostname= fileReader.readLine();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                fileReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        model.addAttribute("pageNum", pageNum);
        model.addAttribute("hostname", hostname);
        return "jsp";
    }

    @RequestMapping({"/header"})
    @ResponseBody
    public String header(HttpServletRequest request, HttpServletResponse response) {
        StringBuffer sql = new StringBuffer();
        Enumeration<String> headerNames = request.getHeaderNames();
        do {
            String hname = headerNames.nextElement();
            String hvalue = request.getHeader(hname);

            sql.append(hname + ":" + hvalue + "<br>");

        } while (headerNames.hasMoreElements());

        String remoteHost = request.getRemoteHost();
        int remotePort = request.getRemotePort();
        String remoteAddr = request.getRemoteAddr();


        sql.append("remoteHost:" + remoteHost + "<br>");
        sql.append("remotePort:" + remotePort + "<br>");
        sql.append("remoteAddr:" + remoteAddr + "<br>");
        sql.append("<br>");
        String ipAddr = request.getHeader("X-Forwarded-For");
        sql.append("x-forwarded-for ip:" + ipAddr + "<br>");

        return sql.toString();
    }

}
